from flask import request, jsonify, Blueprint
import json

from models import Singer
from config import static_prefix

bp = Blueprint('singer', __name__, url_prefix='/singer')


@bp.route('/all', methods=['GET'])
def singer_all():
    # 返回所有歌唱家
    singer_list = Singer.query.all()
    res = []
    for i in singer_list:
        res.append({
            'singer_name': i.singer_name,
            'singer_name_e': i.singer_name_e,
            'pic_src': static_prefix + 'picture?type=singer&filename=' + i.pic_src,
            'vocal_part': i.vocal_part
        })
    return jsonify(res)


@bp.route('/detail', methods=['POST'])
def singer_detail():
    data = request.get_json()
    res = {'msg': '操作成功'}
    if 'singer_name' not in data:
        res['msg'] = '请求参数出错'
        return jsonify(res)
    singer = Singer.query.filter_by(singer_name=data['singer_name']).all()
    if len(singer) == 0:
        res['msg'] = '请求的歌剧不存在'
        return jsonify(res)
    singer = singer[0]
    res['singer_name'] = singer.singer_name
    res['singer_name_e'] = singer.singer_name_e
    res['simple_intro'] = singer.simple_intro
    res['pic_src'] = static_prefix + 'picture?type=singer&filename=' + singer.pic_src
    res['vocal_part'] = singer.vocal_part
    res['nation'] = singer.nation
    res['intro_list'] = json.loads(singer.intro_list)
    res['experience_list'] = json.loads(singer.exp_list)
    res['opr_list'] = []
    # 构造opr_list
    sc_list = singer.singer_to_characters
    for sc in sc_list:
        character = sc.character
        res['opr_list'].append({
            'opr_name': character.opr_name,
            'chapter_pic_src': static_prefix + 'picture?type=character&filename=' + character.pic_src,
            'chapter_name': character.character_name
        })
    print(res)
    return jsonify(res)
